package me.huha.zhime.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @Title: DoubleUtil.java
 * @Author: zhuoxun
 * @mail: yepx2013@gmail.com
 * @Todo: 用于计算Double类型的工具类
 * @CreateTime: 2015年10月26日 下午4:21:37
 */
public class DoubleUtils {
	
	/**
	 * 两数相加
	 * @param val2
	 * @param val2
	 * @return
	 */
	public static double add(double val1, double val2) {
		BigDecimal b1 = new BigDecimal(Double.toString(val1));
		BigDecimal b2 = new BigDecimal(Double.toString(val2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * 两数相减
	 * @param val2
	 * @param val2
	 * @return
	 */
	public static double subtract(double val1, double val2) {
		BigDecimal b1 = new BigDecimal(Double.toString(val1));
		BigDecimal b2 = new BigDecimal(Double.toString(val2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 * 两数相乘
	 * @param val2
	 * @param val2
	 * @return
	 */
	public static double multiply(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 两数相除
	 * @param val2
	 * @param val2
	 * @return
	 */
	public static double div(double val1, double val2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("scale 必须大于等于0");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(val1));
		BigDecimal b2 = new BigDecimal(Double.toString(val2));
		return b1.divide(b2, scale, 4).doubleValue();
	}
	
	/**
	 * 四舍五入
	 * @param v
	 * @param scale
	 * @return
	 */
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("scale必须大于等于0");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, 4).doubleValue();
	}
	
	/**
	 * 截断
	 * @param v
	 * @param scale
	 * @return
	 */
	public static double cutOff(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("scale必须大于等于0");
		}
		
		BigDecimal b = new BigDecimal(Double.toString(v));
        return b.setScale(scale, BigDecimal.ROUND_DOWN).doubleValue();
        
	}
	
	public static boolean equals(double num1, double num2) {
		return equals(num1, num2, null);
	}

	public static boolean equals(double num1, double num2, Integer decimalNum) {
		BigDecimal data1 = new BigDecimal(num1);
		BigDecimal data2 = new BigDecimal(num2);
		if (decimalNum != null) {
			data1 = data1.setScale(decimalNum.intValue(), 4);
			data2 = data2.setScale(decimalNum.intValue(), 4);
		}
		return data1.compareTo(data2) == 0;
	}

	
	public static double tworound(double d) {
		DecimalFormat pcpricedfc = new DecimalFormat("##.00");
		return Double.parseDouble(pcpricedfc.format(d));
	}
}
